import Util from "../lib/util.js";
const session = {
	namespaced: true,
	state: {
		user: {
			id: 0,
			avatar: '/UploadPictures/logo.png',
			name: '',
			userName: '',
			emailAddress: '',
			phoneNumber: ''
		},
		/**
		 * 是否需要强制登录
		 */
		forcedLogin: false,
		hasLogin: false,
		keywords: '输入搜索关键字'
	},
	mutations: {
		setUser(state, user) {
			if (user) {
				state.user = user;
				state.hasLogin = true;
			} else {
				state.hasLogin = false;
				uni.clearStorage();
			}
		},
		setAvatar(state, url) {
			state.user.avatar = url;
		},
		setRunImage(state, url) {
			state.user.runImage = url;
		},
		setPhoneNumber(state, phoneNumber) {
			state.user.phoneNumber = phoneNumber;
		},
		login(state, accessToken) {
			Util.setToken(accessToken);
			state.hasLogin = true;
		},
		logout(state) {
			state.hasLogin = false;
			state.user = {
				id: 0,
				avatar: '/UploadPictures/logo.png',
				name: '',
				userName: '',
				emailAddress: '',
				phoneNumber: ''
			};
			uni.clearStorage();
		},
		setKeywords(state, keyword) {
			state.keywords = keyword;
		}
	},
	actions: {
		init(context, payload) {
			return this.$http.get('/api/services/app/Session/GetCurrentLoginInformations')
				.then(res => {
					context.commit('setUser', res.data.result.user);
				});
		}
	}
}

export default session;
